import type { Recordable } from '@vben-core/typings';

import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemMenuApi } from '#/api/system/menu';
import type { SystemOperateCategoriesApi } from '#/api/system/operateCategories';
import type { DescriptionItemSchema } from '#/components/description';

import { h, ref } from 'vue';

import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import { handleTree } from '@vben/utils';

import { z } from '#/adapter/form';
import { getMenuList } from '#/api/system/menu';
import { getOAuth2ClientList } from '#/api/system/oauth2/client';
import { getOperateCategoriesList } from '#/api/system/operateCategories';
import { ColorPicker } from '#/components/color-picker';
import { DictBadge } from '#/components/dict-badge';

import DictTag from '../../../components/dict-tag/dict-tag.vue';

export const reviewRate = ref(0);
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'parentId',
      label: '父分类',
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getOperateCategoriesList({});
          data.unshift({
            id: 0,
            name: '顶级分类',
          });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择上级分类',
        treeDefaultExpandAll: true,
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      rules: z.number().default(CommonStatusEnum.ENABLE),
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        placeholder: '请选择状态',
      },
    },
    {
      fieldName: 'code',
      label: '分类编码',
      rules: 'required',
      component: 'Input',
      componentProps: {
        placeholder: '请输入分类编码',
      },
    },
    {
      fieldName: 'name',
      label: '分类名称',
      rules: 'required',
      component: 'Input',
      componentProps: {
        placeholder: '请输入分类名称',
      },
    },
    {
      fieldName: 'icon',
      label: '图标',
      component: 'IconPicker',
      componentProps: {
        placeholder: '请选择分类图标',
        prefix: 'carbon',
      },
    },
    {
      fieldName: 'color',
      label: '颜色',
      component: 'ColorPicker',
      componentProps: {
        placeholder: '请输入颜色',
        showAlpha: false,
      },
    },

    {
      fieldName: 'sort',
      label: '排序',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入排序',
      },
    },
    {
      fieldName: 'systemFlag',
      label: '系统内置',
      component: 'RadioGroup',
      defaultValue: false,
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
    {
      fieldName: 'clientId',
      label: '所属应用',
      component: 'ApiSelect',
      componentProps: {
        api: getOAuth2ClientList,
        labelField: 'name',
        valueField: 'clientId',
        autoSelect: 'first',
      },
    },
    {
      fieldName: 'menuId',
      label: '菜单',
      help: '分配到指定菜单下，例如 系统管理',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['clientId'],
        componentProps: (values) => {
          return {
            allowClear: true,
            key: values.parentMenuId || 'all',
            api: async () => {
              const data = await getMenuList({
                clientId: values.clientId,
              });
              data.unshift({
                id: 0,
                name: '顶级菜单',
              } as SystemMenuApi.Menu);
              return handleTree(data);
            },
            class: 'w-full',
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请先选择应用名称',
            filterTreeNode(input: string, node: Recordable<any>) {
              if (!input || input.length === 0) {
                return true;
              }
              const name: string = node.label ?? '';
              if (!name) return false;
              return name.includes(input) || $t(name).includes(input);
            },
            showSearch: true,
            treeDefaultExpandedKeys: [0],
          };
        },

        trigger(values, formApi) {
          // 清空值，避免残留
          formApi.setFieldValue('parentMenuId', undefined);
        },
        renderComponentContent() {
          return {
            title({ label, icon }: { icon: string; label: string }) {
              const components = [];
              if (!label) return '';
              if (icon) {
                components.push(h(IconifyIcon, { class: 'size-4', icon }));
              }
              components.push(h('span', { class: '' }, $t(label || '')));
              return h('div', { class: 'flex items-center gap-1' }, components);
            },
          };
        },
      },
    },
    {
      fieldName: 'component',
      label: '组件路径',
      component: 'Input',
      componentProps: {
        placeholder: '请输入组件路径',
      },
    },
    {
      fieldName: 'formId',
      label: '表单',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请选择动态表单',
      },
    },
    {
      fieldName: 'reqType',
      label: '请求方法',
      component: 'Select',
      componentProps: {
        placeholder: '请选择接口请求方法',
        options: [
          {
            label: 'get',
            value: 'get',
          },
          {
            label: 'post',
            value: 'post',
          },
          {
            label: 'put',
            value: 'put',
          },
          {
            label: 'del',
            value: 'del',
          },
          {
            label: 'download',
            value: 'download',
          },
        ],
      },
    },
    {
      fieldName: 'url',
      label: '接口地址',
      component: 'Input',
      componentProps: {
        placeholder: '请输入接口地址',
      },
    },

    {
      fieldName: 'classPath',
      label: '类路径',
      component: 'Input',
      componentProps: {
        placeholder: '请输入类路径',
      },
    },
    {
      fieldName: 'method',
      label: '类方法',
      component: 'Input',
      componentProps: {
        placeholder: '请输入类方法',
      },
    },
    {
      fieldName: 'metadata.reviewType',
      label: '审核类型',
      component: 'Select',
      componentProps(values) {
        return {
          placeholder: '请选择审核类型',
          options: [
            {
              label: '不开启',
              value: '0',
            },
            {
              label: '简单审核',
              value: '1',
            },
            {
              label: '工作流',
              value: '2',
            },
          ],
          onChange: (val) => {
            reviewRate.value = val === '1' ? 1 : 0;
            values.metadata.reviewRate = reviewRate.value;
          },
        };
      },

      rules: 'required',
    },
    {
      fieldName: 'metadata.draftFlag',
      label: '启用草稿',
      component: 'RadioGroup',
      defaultValue: false,
      componentProps: {
        options: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        buttonStyle: 'solid',
        optionType: 'button',
      },
    },
    {
      fieldName: 'metadata.reviewRate',
      label: '审核级数',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入审核级数',
        onChange: (val) => {
          reviewRate.value = val;
        },
      },
      dependencies: {
        triggerFields: ['metadata'],
        show: (values) => {
          return values.metadata.reviewType === '1';
        },
      },
    },

    {
      fieldName: 'operating',
      label: '操纵期控制规则',
      component: 'Input',
      componentProps: {
        placeholder: '请输入操纵期控制规则',
      },
    },
    {
      fieldName: 'description',
      label: '分类描述',
      component: 'Textarea',
      formItemClass: 'col-span-2',
      componentProps: {
        rows: 4,
        placeholder: '请输入分类描述',
      },
    },
  ];
}

/** 详情页字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      label: '分类编码',
      field: 'code',
    },
    {
      label: '分类名称',
      field: 'name',
    },
    {
      label: '父级分类',
      field: 'parentName',
    },
    {
      label: '分类描述',
      field: 'description',
      render: (val) =>
        h('div', {
          innerHTML: val,
          class: 'whitespace-pre-wrap text-sm leading-relaxed',
        }),
    },
    {
      label: '图标',
      field: 'icon',
      render: (val, data) => {
        return val
          ? h(IconifyIcon, {
              icon: val,
              color: data?.color,
            })
          : '无';
      },
    },
    {
      label: '颜色',
      field: 'color',
      render: (val) => {
        return val
          ? h(ColorPicker, {
              modelValue: val,
              disabled: true,
            })
          : '无';
      },
    },
    {
      label: '状态',
      field: 'status',
      render: (val) =>
        h(DictTag, {
          type: DICT_TYPE.COMMON_STATUS,
          value: val,
        }),
    },
    {
      label: '排序',
      field: 'sort',
    },
    {
      label: '分类路径',
      field: 'codePath',
    },
    {
      label: 'id路径',
      field: 'path',
    },
    {
      label: '系统内置',
      field: 'systemFlag',
      render: (val) =>
        h(DictBadge, {
          value: val,
        }),
    },
    {
      label: '菜单名称',
      field: 'menuName',
    },
    {
      label: '请求类型',
      field: 'reqType',
    },
    {
      label: '接口地址',
      field: 'url',
    },
    {
      label: '组件路径',
      field: 'component',
    },
    {
      label: '类路径',
      field: 'classPath',
    },
    {
      label: '类方法',
      field: 'method',
    },
    {
      label: '操纵期控制规则',
      field: 'operating',
    },
    {
      label: '审核类型',
      field: 'metadata.reviewType',
      render: (val) => {
        const map = {
          '0': '不开启',
          '1': '简单审核',
          '2': '工作流',
        };
        return map[val] || '-';
      },
    },
    {
      label: '启用草稿',
      field: 'metadata.draftFlag',
      render: (val) =>
        h(DictBadge, {
          value: val,
        }),
    },
    {
      label: '审核级数',
      field: 'metadata.reviewRate',
      show: (values) => values?.metadata?.reviewType === '1',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'code',
      label: '分类编码',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入分类编码',
      },
    },
    {
      fieldName: 'name',
      label: '分类名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入分类名称',
      },
    },
    {
      fieldName: 'parentId',
      label: '父分类',
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getOperateCategoriesList({});
          data.unshift({
            id: 0,
            name: '顶级分类',
          });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择上级分类',
        treeDefaultExpandAll: true,
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        placeholder: '请选择状态',
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<SystemOperateCategoriesApi.OperateCategories>['columns'] {
  return [
    {
      field: 'id',
      title: '业务分类id',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'name',
      title: '分类名称',
      minWidth: 300,
      treeNode: true,
    },
    {
      field: 'code',
      title: '分类编码',
      minWidth: 120,
    },
    {
      field: 'parentId',
      title: '父级分类ID',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'icon',
      title: '图标',
      minWidth: 100,
      slots: { default: 'icon' },
    },
    {
      field: 'color',
      title: '颜色',
      minWidth: 100,
      slots: { default: 'color' },
    },
    {
      field: 'status',
      title: '状态',
      minWidth: 80,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.COMMON_STATUS },
      },
    },
    {
      field: 'sort',
      title: '排序',
      minWidth: 80,
    },
    {
      field: 'systemFlag',
      minWidth: 80,
      title: '系统内置',
      cellRender: {
        name: 'CellDictBadge',
      },
    },
    {
      field: 'codePath',
      title: '分类路径',
      minWidth: 180,
    },
    {
      field: 'path',
      title: 'id路径',
      minWidth: 180,
    },
    {
      field: 'actions',
      title: '操作',
      width: 280,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
